import React from 'react';
import { Modal, Form, Icon, message, TreeSelect } from 'antd';
import { connect } from 'umi';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import { get as getPath } from 'object-path';
import { customUpload } from '@/utils/fileUpload';
import styles from './index.less';
import { getEmployeeList } from '../../services';

const formLayout = {
    wrapperCol: { span: 24 },
    labelCol: { span: 0 }
};

// 不允许添加尺寸大于10M的文件
const myValidateFn = file => {
    if (file.size > 1024 * 1024 * 10) {
        message.error('图片不能大于10M！');
        return false;
    }
    return true;
};

const ChildTaskMoreSimple = ({ form, visible, setVisible, user, onOk, taskDetail, onCancel }) => {
    const { getFieldDecorator } = form;
    const [employeeList, setEmployeeList] = React.useState([]);

    const handleOk = () => {
        const params = form.getFieldsValue();
        const { taskDesc } = params;
        if (taskDesc && taskDesc.toHTML().length > 20000) {
            message.error('任务描述内容过多');
            return;
        }
        if (onOk) {
            onOk({
                ...params,
                taskDesc: taskDesc && taskDesc.toHTML()
            });
        }
        setVisible(false);
    };

    const handleCancel = () => {
        if (onCancel) onCancel();
        setVisible(false);
    };

    const getEmployeeListAsync = async companyId => {
        const res = await getEmployeeList(companyId);
        if (res && res.code === 10000) {
            const { data } = res;
            const arr = data.map(item => ({
                ...item,
                value: item.employeeCode,
                title: item.employeeName
            }));
            setEmployeeList(arr);
        }
    };

    const myUploadFn = param => {
        const onSuccess = (response, file) =>
            param.success({
                url: response.data[0].url,
                meta: {
                    id: file.name,
                    title: file.name,
                    alt: file.name
                }
            });
        customUpload({ files: param, onSuccess });
    };

    const handleEditorChange = editorState => {
        const html = editorState.toHTML();
        if (html.length > 20000) {
            message.error('任务描述内容过多');
        }
    };

    React.useEffect(() => {
        getEmployeeListAsync(user.companyId);
    }, [user.companyId]);

    const controls = [
        'undo',
        'redo',
        'font-size',
        'text-color',
        'bold',
        'italic',
        'underline',
        'strike-through',
        'text-indent',
        'text-align',
        'list-ul',
        'list-ol',
        'media',
        'hr',
        'clear'
    ];

    return (
        <Modal
            title="新增子任务-更多信息"
            width={900}
            centered
            visible={visible}
            onOk={handleOk}
            destroyOnClose
            keyboard={false}
            maskClosable={false}
            onCancel={handleCancel}
        >
            <Form {...formLayout} style={{ marginLeft: 20, marginRight: 20 }}>
                <Form.Item label="">
                    <div
                        style={{
                            position: 'relative',
                            display: 'flex',
                            height: 40,
                            alignItems: 'center',
                            margin: '10px 0 0'
                        }}
                        title="参与人"
                    >
                        <div
                            style={{
                                position: 'absolute',
                                left: 0,
                                top: '50%',
                                transform: 'translateY(-50%)',
                                padding: '0 10px',
                                zIndex: 0
                            }}
                        >
                            <Icon type="user" />
                        </div>
                        {getFieldDecorator('participantEmployeeCodeList', {
                            initialValue: getPath(taskDetail, 'participantEmployeeCodeList') || []
                        })(
                            <TreeSelect
                                multiple
                                allowClear
                                showSearch
                                maxTagCount={8}
                                className={styles.participant}
                                style={{ display: 'block', flex: 1 }}
                                placeholder="请选择参与人"
                                dropdownClassName={styles.treeSelectDropDown}
                                dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                getPopupContainer={trigger => trigger.parentNode}
                                treeNodeFilterProp="title"
                                treeData={employeeList}
                            ></TreeSelect>
                        )}
                    </div>
                    {/* {getFieldDecorator('participantEmployeeCodeList', {
                        initialValue: getPath(taskDetail, 'participantEmployeeCodeList') || []
                    })(
                        <TreeSelect
                            multiple
                            showArrow
                            allowClear
                            showSearch
                            maxTagCount={10}
                            suffixIcon={<Icon type="user" />}
                            placeholder="请选择参与人"
                            dropdownClassName={styles.fixedSelect}
                            dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                            getPopupContainer={trigger => trigger.parentNode}
                            treeDefaultExpandAll
                            treeNodeFilterProp="title"
                            treeData={employeeList}
                        ></TreeSelect>
                    )} */}
                </Form.Item>
                <Form.Item label="">
                    {getFieldDecorator('taskDesc', {
                        initialValue: getPath(taskDetail, 'taskDesc')
                            ? BraftEditor.createEditorState(`${getPath(taskDetail, 'taskDesc')}`)
                            : BraftEditor.createEditorState(null)
                    })(
                        <BraftEditor
                            media={{
                                uploadFn: myUploadFn,
                                validateFn: myValidateFn,
                                accepts: {
                                    image: 'image/png,image/jpeg,image/gif'
                                }
                            }}
                            onChange={handleEditorChange}
                            controls={controls}
                            excludeControls={['fullscreen']}
                            imageControls={[
                                {
                                    onClick: block => {
                                        console.log(block);
                                    } // 指定控件点击后的回调，参数为当前图片的block对象
                                },
                                'align-left',
                                'align-center',
                                'align-right',
                                'size',
                                'remove'
                            ]}
                            placeholder="请输入任务描述"
                            className={styles.customBraftEditor}
                            // contentStyle={{ height: 120 }}
                            style={{
                                border: '1px solid #d9d9d9',
                                borderTopWidth: '1.02px',
                                borderRadius: '4px',
                                marginTop: '4px'
                            }}
                        />
                    )}
                </Form.Item>
            </Form>
        </Modal>
    );
};

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(ChildTaskMoreSimple));
